package com.cash.channel.svc.service.common;

import com.cash.channel.api.exception.CashChannelException;
import com.cash.channel.svc.dao.ThirdIdMappingMapper;
import com.cash.channel.svc.logic.OrderLogic;
import com.cash.channel.svc.logic.RepayLogic;
import com.cash.channel.svc.service.base.LoanStatus;
import com.alibaba.fastjson.JSON;
import com.cash.channel.api.constant.Constant;
import com.cash.channel.api.model.ApiRequestModel;
import com.cash.channel.api.model.ApiResponseModel;
import com.cash.channel.api.model.repay.WdOrderInfoModel;
import com.cash.channel.api.model.request.LoanStatusRequest;
import com.cash.channel.api.model.response.LoanStatusResponse;
import com.cash.channel.api.model.user.ThirdIdModel;
import geex.core.service.LoanService;
import geex.core.service.model.loan.Loan;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;


/**
 * @author zhuweiqiang
 */
@Slf4j
@Service(Constant.CHANNEL.COMMON + Constant.SERVICE.查询放款结果)
public class CommonLoanStatus implements LoanStatus {

    @Autowired(required = false)
    private ThirdIdMappingMapper thirdIdMappingMapper;

    @Autowired
    private RepayLogic repayLogic;

    @Autowired
    private LoanService loanService;

    @Autowired
    private OrderLogic orderLogic;

    @Override
    public ApiResponseModel<LoanStatusResponse> doLoanStatus(ApiRequestModel apiRequestModel) {
        LoanStatusRequest loanStatusRequest = JSON.parseObject(apiRequestModel.getData(), LoanStatusRequest.class);
        try {
            LoanStatusResponse loanStatusResponse = new LoanStatusResponse();
            loanStatusResponse.setOrderNo(loanStatusRequest.getOrderNo());

            WdOrderInfoModel wdOrderInfoModel = repayLogic.findWithdrawAppInfoByAppId(loanStatusRequest.getWithdrawId());
            loanStatusResponse.setLoanAmount(wdOrderInfoModel.getNWdAmt().setScale(2, RoundingMode.HALF_UP));
            loanStatusResponse.setOrderStatus(orderLogic.getOrderStatus(wdOrderInfoModel, null));
            if (1500 == wdOrderInfoModel.getNWdAppStatus()) {
                loanStatusResponse.setRepayPlan(repayLogic.getRepayPlan(loanStatusRequest.getWithdrawId()));
                Loan loan = loanService.findLoanByExtId(wdOrderInfoModel.getCWdAppId());
                loanStatusResponse.setLoanDate(DateFormatUtils.format(loan.getLoanDate(), "yyyy/MM/dd HH:mm:ss"));
                loanStatusResponse.setOrderStatus(orderLogic.getOrderStatus(wdOrderInfoModel, loan));
            }
            return new ApiResponseModel<>(true, 0, "", loanStatusResponse);
        } catch (CashChannelException e) {
            log.error("通过订单号:{}获取产品信息异常:{}",loanStatusRequest.getOrderNo(), e.getMessage(),e);
            return new ApiResponseModel<>(false,0,"获取产品信息异常",null);
        }
    }
}
